package com.daiziru.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daiziru.VO.PostVO;
import com.daiziru.common.Result;
import com.daiziru.common.constant.RedisConstants;
import com.daiziru.config.RabbitConfig;
import com.daiziru.entity.MPost;
import com.daiziru.search.mq.PostMqIndexMessage;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 作者：無言
 * 时间：2022/12/19 9:57
 * 描述：永无BUG
 * 管理员操作帖子的接口
 */

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController{

    @ResponseBody
    @PostMapping("/jie-set")
    public Result AdminSet(Long id ,Integer rank, String field) {
        MPost post = postService.getById(id);
        Assert.notNull(post, "该文章已经被删除了!");
        //删除帖子
        if("delete".equals(field)) {
            postService.removeById(id);
            //判断文章是否属于本周热议，属于则需要删除相关redis
            String dayRank = RedisConstants.DAY_RANK + DateUtil.format(post.getCreated(), DatePattern.PURE_DATE_FORMAT);
            //查找redis的zset中元素的下标，不存在返回null
            Long index = redisTemplate.opsForZSet().rank(dayRank, id);
            if(index != null) {
                redisTemplate.opsForZSet().remove(dayRank,id);
            }
            boolean b = redisUtil.hasKey(RedisConstants.RANK_POST+id);
            if(b) {
                redisUtil.del(RedisConstants.RANK_POST+id);
            }
            // 本周热议重新做并集
            postService.zUnionAndStoreLast7DayForWeekRank();
            // 通知消息给mq，告知更新或添加
            amqpTemplate.convertAndSend(
                    RabbitConfig.ES_EXCHANGE,
                    RabbitConfig.ES_BIND_KEY,
                    new PostMqIndexMessage(post.getId(), PostMqIndexMessage.REMOVE) //发送的内容
            );
            return Result.fail("删除成功").action("/index");
        } else if("status".equals(field)) {
            //贴子是否设为精品文章
            post.setRecommend(rank == 1);
        } else if("stick".equals(field)) {
            //文章是否置顶
            post.setLevel(rank);
        }
        postService.updateById(post);
        return Result.success();
    }

    /**
     * 分批次同步文章数据到es,每次同步10000条
     * @return
     */
    @ResponseBody
    @PostMapping("/initEsData")
    public Result initEsData() {
        int size = 10000;
        Page page = new Page();
        page.setSize(size);
        long total = 0;
        for (int i = 1; i < 1000; i ++) {
            page.setCurrent(i);
            IPage<PostVO> paging = postService.selectByPage(page,null,null,null,null,null);
            int num = searchService.initEsData(paging.getRecords());
            total += num;
            // 当一页查不出10000条的时候，说明是最后一页了
            if(paging.getRecords().size() < size) {
                break;
            }
        }
        return Result.success("ES索引初始化成功，共 " + total + " 条记录！", null);
    }
}
